﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Net;
using System.Xml.Linq;
using AuchanScan.Models;
using AuchanScan.Tools;

namespace AuchanScan.ViewModels
{
    public class SyncViewModel : INotifyPropertyChanged
    {
        public float Progress { get; set; }

        public bool Loading { get; set; }

        public void Sync()
        {
           var wc = new WebClient();
            wc.DownloadProgressChanged += wc_DownloadProgressChanged;
            wc.OpenReadAsync(new Uri(Config.BASE_URI+"/auchan/datas.xml", UriKind.Absolute));
            wc.OpenReadCompleted += wc_OpenReadCompleted;
            Loading = true;
            RaisePropertyChanged("Loading");
        }


        private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            var nfi = new NumberFormatInfo {NumberDecimalSeparator = "."};

            XElement root = XElement.Load(e.Result);

            var products = new List<Product>();
            foreach (XElement elem in root.Element("products").Elements("product"))
            {
                products.Add(new Product
                    {
                        IsTicketRestoCompliant = elem.Attribute("ticketresto")!=null?elem.Attribute("ticketresto").Value == "true":false,
                        Id=int.Parse(elem.Attribute("id").Value),
                        Name = elem.Attribute("name").Value,
                        Barcode = long.Parse(elem.Attribute("barcode").Value),
                        Price = double.Parse(elem.Attribute("price").Value, nfi)
                    });
            }


            ProductDatabase.Instance.SetProducts(products);
            Loading = false;
            RaisePropertyChanged("Loading");
            NavigationServiceHelper.Instance.GoBack();
        }

        private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Progress = (float) e.ProgressPercentage/100;
            RaisePropertyChanged("Progress");
        }

        #region PropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(String name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

        #endregion

        
    }
}